const app = getApp();
import { jiatuiRequest } from "/utils/requests";
import domains from "../../config/domains";
const domainKey = 'jiatui';
Page({
  data: {
    navTop: app.globalData.navTop,
    statusBarHeight: app.globalData.statusBarHeight,
    titleBarHeight: app.globalData.titleBarHeight,
    yl: 1,
    isShowAuth: !1,
    userInfo: null,
    my_result: null,
  },
  async onLoad(options) {
    this.setData(await app.methods.myPhone()); // 获取本地存储手机号
    if (!this.data.myPhone) {
      await app.methods.getPhoneNumber()
    }
    xhs.showShareMenu({
      shareTypes: 'normal',
    })
    xhs.showLoading({
      title: "数据加载中...",
    });
    let a = this;
    xhs.getSystemInfo({
      success: function (e) {
        app.globalData || (app.globalData = {}),
          -1 !== e.model.indexOf("iPhone")
            ? (app.globalData.titleBarHeight = 44)
            : (app.globalData.titleBarHeight = 48),
          (app.globalData.statusBarHeight = e.statusBarHeight),
          a.setData({
            statusBarHeight: app.globalData.statusBarHeight,
            titleBarHeight: app.globalData.titleBarHeight,
          });
      },
      failure: function () {
        a.setData({
          statusBarHeight: 0,
          titleBarHeight: 0,
        });
      },
    });
    let links, jxOptions;
    if (options.scene) {
      options.scene = options.scene.replace(/%253D/g, ".");
      options.scene = options.scene.replace(/%2526/g, "-");
      jxOptions = await app.methods.getOPtions(options);
    }
    let id = options.scene ? jxOptions.id : options.id;
    options.id = id;
    links = await app.methods.getLink(id);
    options.fx = options.scene ? jxOptions.fx : options.fx;
    options.gh = options.scene ? jxOptions.gh : options.gh;
    options.hdid = links.hdid ? links.hdid : 1;
    options.actid = links.actid ? links.actid : '57058';
    this.setData({
      options,
    })
    this.setData(await app.methods.getIdentity(options)); // 获取个人身份信息
    if (this.data.getIdentity.crm) {
      options.wxh = this.data.getIdentity.crm
    } else {
      options.wxh = options.gh
    }
    this.setData(await app.methods.getWechat(options)); // 获取个人身份信息
    this.setData(await app.methods.guishudi(options)); // 获取归属地
    let fenbu = this.data.fenbu;
    let fenxiao = this.data.fenxiao;
    let getIdentity = this.data.getIdentity;
    getIdentity.fenbu = fenbu;
    getIdentity.fenxiao = fenxiao;
    getIdentity.zzname = this.data.zzname;
    getIdentity.zzid = this.data.zzid;
    getIdentity.erpdqm = this.data.erpdqm;
    await this.getPrices(options.hdid);
    let getUserRes = await this.isJoined();
    if (getUserRes.code == 0) {
      let authorizeInfo = await app.methods.authorizeInfo("scope.userInfo");
      this.setData({
        authorizeInfo,
        isJoined: true,
      })
    } else {
      this.setData({
        isJoined: false,
      })
    }
    if (this.data.myPhone) {
      this.setData(await app.methods.getphonestatusCX(this.data.myPhone, this.data.options.actid, 'chaxun'))
    }
    this.setData({
      getIdentity
    })
    xhs.showLoading({
      title: "数据加载完成",
    });
    setTimeout(() => {
      xhs.hideLoading();
    }, 1500);
    console.log(this.data)
  },

  // 获取活动信息
  getPrices(activity_id) {
    return new Promise(resolve => {
      jiatuiRequest({
        url: `/api/v1/lottery/getActivity`,
        method: 'GET',
        dataType: 'jsonp',
        header: {
          'X-Requested-From': 'WeChatMiniProgram'
        },
        data: {
          activity_id
        },
      }).then(async res => {
        const { code, data } = res;
        if (code !== 0) xhs.showToast({
          title: res.msg,
          icon: 'fail',
          duration: 1500,
          mask: true,
        });
        let { activity, prizes, participants, count } = data;
        activity.draw_time1 = this.toTs(activity.draw_time)
        this.setData({
          activity,
          prizes,
          participants,
          count,
          autoplay: prizes.length > 1 ? true : false,
          indicatorDots: prizes.length > 1 ? true : false,
        })
        if (activity.status == 1) {
          let winnerLists = await this.getWinners()
          this.setData({
            winnerLists: winnerLists.data.winnersLists,
            my_result: winnerLists.data.my_result
          })
        }
        resolve()
      }).catch(err => {
        // console.log(err)
        xhs.showToast({
          title: res.msg,
          icon: 'fail',
          duration: 1500,
          mask: true,
        });
        resolve()
      })
    })
  },

  // 点击报名
  async onJoin() {
    let { myPhone } = this.data;
    if (!myPhone) {
      this.setData({
        isShowAuth: !0
      })
      return;
    }
  },

  // 授权
  async getUserInfo(e) {
    let { userInfo, activity, myPhone } = this.data;
    if (e.detail.userInfo && e.detail.userInfo.avatarUrl) {
      userInfo = e.detail.userInfo;
      await app.methods.setStorage("userInfo", userInfo);
      xhs.downloadFile({
        url: userInfo.avatarUrl,
        success: (async res => {
          this.setData({
            userInfo,
            avatarUrl: res.tempFilePath,
          })
          if (activity.draw_status === 2) {
            xhs.showToast({
              title: '正在开奖请稍后',
              icon: 'fail',
              duration: 1500,
              mask: true,
            });
            return;
          }
          if (activity.draw_status === 1) {
            xhs.showToast({
              title: '已开奖下次再来',
              icon: 'fail',
              duration: 1500,
              mask: true,
            });
          }
          let updateAvatar = await app.methods.updateAvatar(res.tempFilePath)
          updateAvatar = JSON.parse(updateAvatar)
          const { code, data } = updateAvatar;
          if (code !== 0) {
            xhs.showToast({
              title: updateAvatar.msg,
              icon: 'fail',
              duration: 1500,
              mask: true,
            });
            return;
          }
          let { path } = data.files[0];
          path = path.replaceAll('\\', '/')
          const avatar = `${domains[domainKey]}/${path}`
          // 报名
          let bmRes = await this.clickSignUp(avatar, myPhone)
          if (bmRes.code !== 0) {
            xhs.showToast({
              title: bmRes.msg,
              icon: 'fail',
              duration: 1500,
              mask: true,
            });
            return;
          } else {
            xhs.showToast({
              title: '报名成功',
              icon: 'success',
              duration: 1500,
              mask: true,
            });
            if (!this.data.user) {
              await app.methods.registerCX(this.data.myPhone, this.data.options.actid, this.data.activity.name, '', this.data.getIdentity, '', '', this.data.book, 'chaxun')
              this.setData(await app.methods.getphonestatusCX(this.data.myPhone, this.data.options.actid, 'chaxun'))
            }
            let getParticipants = await this.getParticipantsCount()
            this.setData({
              isJoined: true,
              count: getParticipants.data.count,
              participants: getParticipants.data.participants,
            })
          }
        })
      })
    } else {
      let getAuthInfo = await app.methods.getAuth("scope.userInfo");
      if (getAuthInfo.errMsg !== 'authorize:ok') {
        xhs.showToast({
          title: '您未授权',
          icon: 'fail',
          duration: 1500,
          mask: true,
        });
        if (getAuthInfo.code == -2) {
          setTimeout(() => {
            xhs.openSetting({
              success: function (res) {
                // console.log(res)
              }
            })
          }, 1500)
        }
        return;
      }
    }
  },

  // 解析开奖时间
  toTs(drawTimeStr) {
    const utcDate = new Date(drawTimeStr);
    const pad = (n) => n.toString().padStart(2, '0');
    const year = utcDate.getFullYear();
    const month = pad(utcDate.getMonth() + 1);
    const day = pad(utcDate.getDate());
    const hours = pad(utcDate.getHours());
    const minutes = pad(utcDate.getMinutes());
    const seconds = pad(utcDate.getSeconds());
    return `${month}月${day}日 ${hours}:${minutes}:${seconds}`;
  },

  // 点击报名
  clickSignUp(avatar, myPhone) {
    return new Promise((resolve, reject) => {
      jiatuiRequest({
        url: `/api/v1/lottery/joinActivity`,
        method: "POST",
        dataType: "jsonp",
        header: {
          "x-requested-from": "WeChatMiniProgram",
        },
        data: {
          activity_id: this.data.options.hdid,
          phone: myPhone,
          nickname: this.data.userInfo.nickName,
          avatar,
        },
      }).then(res => {
        // console.log(res)
        resolve(res)
      }).catch(err => {
        // console.log(err)
        reject(err)
      })
    });
  },

  // 查询是否报名
  async isJoined() {
    let { myPhone } = this.data;
    return new Promise((resolve, reject) => {
      jiatuiRequest({
        url: `/api/v1/lottery/isJoined`,
        method: "GET",
        dataType: "jsonp",
        header: {
          "x-requested-from": "WeChatMiniProgram",
        },
        data: {
          activity_id: this.data.options.hdid,
          phone: myPhone,
        },
      }).then(res => {
        // console.log(res)
        resolve(res)
      }).catch(err => {
        // console.log(err)
        reject(err)
      })
    })
  },

  // 查询报名人数
  getParticipantsCount() {
    return new Promise((resolve, reject) => {
      jiatuiRequest({
        url: '/api/v1/lottery/getParticipantsCount',
        method: 'GET',
        header: {
          "x-requested-from": "WeChatMiniProgram",
        },
        data: {
          activity_id: this.data.options.hdid,
        },
      }).then(res => {
        // console.log(res)
        resolve(res)
      }).catch(err => {
        // console.log(err)
        reject(err)
      })
    })
  },

  // 开奖后获取中奖信息
  getWinners: function () {
    return new Promise((resolve, reject) => {
      jiatuiRequest({
        url: '/api/v1/lottery/getWinners',
        method: 'GET',
        header: {
          "x-requested-from": "WeChatMiniProgram",
        },
        data: {
          phone: this.data.myPhone,
          activity_id: this.data.options.hdid,
        },
      }).then(res => {
        // console.log(res)
        resolve(res)
      }).catch(err => {
        // console.log(err)
        reject(err)
      })
    })
  },
  async user_login(e) {
    if (typeof e.detail == 'boolean') {
      this.setData({
        isShowAuth: e.detail
      })
    } else {
      this.setData({
        myPhone: e.detail
      })
      let getUserRes = await this.isJoined();
      if (getUserRes.code == 0) {
        let authorizeInfo = await app.methods.authorizeInfo("scope.userInfo");
        this.setData({
          authorizeInfo,
          isJoined: true,
        })
      } else {
        this.setData({
          isJoined: false,
        })
      }
      this.setData(await app.methods.getphonestatusCX(e.detail, this.data.options.actid, 'chaxun'))
    }
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    let { fx = 'hbwtb', gh = 'zcj37368', id } = this.data.options;
    let { share_img, share_font } = this.data.activity;
    return {
      title: share_font,
      path: `/packageA/lottery/index?id=${id}&fx=${fx}&gh=${gh}`,
      imageUrl: share_img,
    }
  },
})